#!/bin/sh /etc/rc.common

START=96
STOP=96

PATH=/opt/sbin:/opt/bin:/opt/usr/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

config_load smartvpn
config_get VPN_ENABLE global vpn_enable 0
config_get VPN_INIT_CMD global init_cmd ""

smartvpn_init(){
	# check if first time installation
	if [[ ! -d /etc/smartvpn/backup ]]; then
		VPN_INIT_CMD="--lanip all"
	fi
	if [[ -n "$VPN_INIT_CMD" ]]; then
		logger -s -t softether "Executing SmartVPN init command: $VPN_INIT_CMD"
		/usr/share/smartvpn/smartvpnconfig.sh --norestart $VPN_INIT_CMD
		if [ $? -eq 0 ]; then
			uci set smartvpn.global.init_cmd=""
			uci commit smartvpn
		fi
	fi
}

ipset_create(){
    local _ipset=$1
    local _type=${2:-ip}

    ipset list | grep $_ipset > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        ipset create $_ipset hash:$_type > /dev/null 2>&1
    else
        [[ "$2" != "soft" ]] && ipset flush $_ipset
    fi    
}

start() {
	# check if init is needed
	smartvpn_init
	# create ipsest anyway
	ipset_create ip_oversea
    ipset_create ip_hongkong
    ipset_create ip_mainland
	ipset_create net_oversea net
    ipset_create net_hongkong net
    ipset_create net_mainland net

	if [ $VPN_ENABLE == 1 ]; then
		logger -s -t softether "Starting SmartVPN..."
		smartvpn.sh on hard
	else
		logger -s -t softether "SmartVPN is disabled"
	fi
}

stop() {
	logger -s -t softether "Stoping SmartVPN..."
	smartvpn.sh off
}

restart() {
	start
}

reload() {
	# check if init is needed
	smartvpn_init	
	if [ $VPN_ENABLE == 1 ]; then
		logger -s -t softether "Reloading SmartVPN...（hard）"
		smartvpn.sh on hard
	else
		logger -s -t softether "Stoping SmartVPN..."
		smartvpn.sh off
	fi
}
